package com.derbtec.refale.transaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.derbtec.refale.R;
import com.derbtec.refale.activities.EventListViewActivity;
import com.derbtec.refale.models.Event;
import com.derbtec.refale.models.User;
import com.derbtec.refale.util.HelperUtils;
import com.derbtec.refale.util.Session;

public class GetEventsAsyncTask extends AsyncTask<String, Integer, Boolean> {
	
	private ArrayList<Event> elementbuffer = new ArrayList<Event>();
	private Activity activity;
	private ProgressDialog pdia;
	
	public GetEventsAsyncTask(Activity activity) {
		this.activity = activity;
	}
	
	protected void onPreExecute(){ 
		   super.onPreExecute();
		        pdia = new ProgressDialog(((EventListViewActivity) activity).getParent());
		        pdia.setTitle(R.string.eventlist);
		        pdia.setMessage("Loading Events...");
		        pdia.show();
		        //pdia.getWindow().setGravity(Gravity.CENTER);
		}
	
	protected Boolean doInBackground(String... params) {
		try {
			HttpParams httpparams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
			DefaultHttpClient client = new DefaultHttpClient(httpparams);
			HttpPost post = new HttpPost("http://derb.square7.ch/jsoneventgetall.php");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			post.setHeader("Cookie", Session.getCookie());
			
			
			
			HttpResponse response = client.execute(post);
			//Log.d("HTTPSTATUS", ""+response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200){

				InputStream is = response.getEntity().getContent();
				BufferedReader bfr = new BufferedReader(new InputStreamReader(is));
				String line = bfr.readLine();
				String newline;
				while ((newline = bfr.readLine()) != null) {
					line += (newline  + "\n");
				}
				Log.d("JSONresponse", line);
				
	
	            JSONArray jArray = new JSONArray(line);  
	            for(int i=0;i<jArray.length();i++){
	            	
	            	try {
	            	
	                JSONObject json_data 	= jArray.getJSONObject(i);
	                
					Event eventbuffer = HelperUtils.EventFromJson(json_data, new Event(), new User());
					addElementbuffer(eventbuffer);
					
					
					
	                //Log.d("JSON", json_data.toString());
					
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	                
	                
	            }
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
		
	}
	
	protected void onProgressUpdate(Integer... progress) {	    
	}
	
	protected void onPostExecute(Boolean result) {
		pdia.dismiss();
		((EventListViewActivity) activity).addElements(elementbuffer);
		((EventListViewActivity) activity).updateData();
		
		
	}

	public ArrayList<Event> getElementbuffer() {
		return elementbuffer;
	}

	public void setElementbuffer(ArrayList<Event> elementbuffer) {
		this.elementbuffer = elementbuffer;
	}
	
	public void addElementbuffer(Event event) {
		this.elementbuffer.add(event);
	}
}
